package com.changjiang.luban.utils.file;

import com.changjiang.luban.utils.GenerateCodeUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Random;

/**
 * TencentCosUtil
 * Description:
 *
 * @author nichangjiang@vip.qq.com
 * @version v0.1
 * @date 2018/6/28 - 9:01
 */
@SuppressWarnings("ALL")
public class TencentCosUtil {



    /** appId */
    private static final String APP_ID = "1256861391";

    /** 密钥id */
    private static final String SECRET_ID = "AKIDJVdaMx8acS6Zq1j1nNmz0qUwDICuMktr";

    /** 密钥key */
    private static final String SECRET_KEY = "vfFdqrhLn37zgBXhgWBh4GF3h9PUNBoG";

    /** 设置bucket所在的区域 华东园区：sh */
    private static final String SH_REGION = "ap-shanghai";

    /** 海报原图存放 */
    public static final String POSTER_BUCKET_NAME = "luban";

    /** 用户海报存放 */
    public static final String USER_POSTER_BUCKET_NAME = "user-luban";

    /** 二维码存放地址 */
    public static final String QRCODE_BUCKET_NAME = "qrcode";

    /** 用户二维码存放地址 */
    public static final String USER_QRCODE_BUCKET_NAME = "user-qrcode";


    /** 二维码存放地址 */
    public static final String NEWS_SHARE_BUCKET_NAME = "news-share";


    private static final COSCredentials CRED = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);

    private static final ClientConfig CLIENT_CONFIG = new ClientConfig(new Region(SH_REGION));

    private static final COSClient COS_CLIENT = new COSClient(CRED, CLIENT_CONFIG);

    private COSClient cOSClient;

    public TencentCosUtil() {
        cOSClient = new COSClient(CRED, CLIENT_CONFIG);
    }

    /**
     * 销毁
     */
    public void destory() {
        cOSClient.shutdown();
    }


    /**
     * 上传图片
     */
    public void uploadImg(String url,String bucketName) throws Exception {
        File fileOnServer = new File(url);
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String[] split = url.split("/");
            this.uploadInputStream(fin, split[split.length - 1],bucketName);
        } catch (FileNotFoundException e) {
            throw new Exception("图片上传失败");
        }
    }

    public String uploadFileImg(File fileOnServer,String bucketName) throws Exception {
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String name =GenerateCodeUtils.getUUId(1)+".jpg";
            this.uploadInputStream(fin, name,bucketName);
            return name.substring(0,name.lastIndexOf("."));
        } catch (FileNotFoundException e) {
            throw new Exception("图片上传失败");
        }
    }


    public String uploadFile(MultipartFile file, String bucketName) throws Exception {
        if (file.getSize() > 10 * 1024 * 1024) {
            throw new Exception("上传图片大小不能超过10M！");
        }
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name =GenerateCodeUtils.getUUId(1)+substring;
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadInputStream(inputStream, name,bucketName);
            return name.substring(0,name.lastIndexOf("."));
        } catch (Exception e) {
            throw new Exception("图片上传失败");
        }
    }

    /**
     * 获得图片路径
     */
    public String getImgUrl(String fileUrl,String bucketName) {
        return getUrl(fileUrl,bucketName);
    }

    /**
     * 获得url链接
     */
    public String getUrl(String key,String bucketName) {
        // 设置URL过期时间为10年 3600l* 1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = COS_CLIENT.generatePresignedUrl(bucketName+"-"+APP_ID, key, expiration);

        if (url != null) {
            return "http://"+url.getHost()+url.getPath();
        }
        return null;
    }

    /**
     * 上传到COS服务器 如果同名文件会覆盖服务器上的
     */
    public String uploadInputStream(InputStream instream, String fileName,String bucketName) {
        String ret = "";
        try {
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            // 上传文件
            PutObjectResult putResult = cOSClient.putObject(bucketName+"-"+APP_ID,  fileName.substring(0,fileName.lastIndexOf(".")), instream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 删除
     * @param bucketName
     * @param key
     */
    public void delete(String bucketName,String key){
        cOSClient.deleteObject(bucketName+"-"+APP_ID,key);
    }

    /**
     * Description: 判断Cos服务文件上传时文件的contentType
     * @param filenameExtension 文件后缀
     * @return String
     */
    private static String getcontentType(String filenameExtension) {
        if (filenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (filenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")
                || filenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (filenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (filenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (filenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (filenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

}
